﻿function AzureOnlineTablesListView(context) {
    var self = this;

    var spinner = new SpinnerModel();

    var tables = context.tables.tables;

    var spaRuntime = context.spaRuntime;

    var tableDetailsRoute = spaRuntime.findRouteByName('tableRecords');

    var filter = ko.observable('');
    
    var details = new AzureOnlineTableCreateDetailsView(context);

    var filteredTables = ko.computed(function() {
        var tbls = tables();
        var f = filter();
        if (utils.isNullOrWhiteSpace(f)) return tbls;
        var wildcard = new Wildcard(f);
        var res = [];
        for (var i = 0; i < tbls.length; i++) {
            var tbl = tbls[i];
            if (wildcard.match(tbl.name())) {
                res.push(tbl);
            }
        }
        return res;
    });
    
    function reload() {
        var api = context.api();
        spinner.enter();
        api.tables.queryTables({
            success: function (raw) {
                spinner.leave();
                var res = [];
                var $doc = $(raw);

                var $items = $doc.find('feed entry');
                $items.each(function () {
                    res.push(new AzureOnlineTableEntry($(this)));
                });

                tables(res);

                spaRuntime.check();
            },
            error: function () {
                spinner.leave();
                tables([]);
                return 'notify';
            }
        });
    }

    context.api.subscribe(function () {
        var api = context.api();
        if (api) {
            reload();
        }
    });

    ko.computed(function() {
        filter(context.tables.tablesSettings().getItem('quickSearch') || '');
    }).extend({throttle: 10});

    ko.computed(function() {
        context.tables.tablesSettings().setItem('quickSearch', filter());
    }).extend({ throttle: 10 });

    self.getTableDetailsUrl = function (table) {
        return tableDetailsRoute.formatHash({
            tableName: table.name()
        });
    };

    self.context = context;
    self.spinner = spinner;
    self.filter = filter;
    self.reload = reload;
    self.tables = tables;
    self.filteredTables = filteredTables;
    self.details = details;
}
